package cn.yudao.org.controller;

import cn.yudao.basic.annotation.PreAuthorize;
import cn.yudao.basic.utils.AjaxResult;
import cn.yudao.basic.utils.LoginContext;
import cn.yudao.basic.utils.PageList;
import cn.yudao.org.domain.Department;
import cn.yudao.org.query.DepartmentQuery;
import cn.yudao.org.service.IDepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/department")
@Api(value = "部门的API",description="部门相关的CRUD功能")
public class DepartmentController {

    @Autowired
    private IDepartmentService service;

    @GetMapping("/{id}")
    @ApiOperation(value = "通过ID查询" )
    public Department loadById(@ApiParam(name="ID属性",required = true) @PathVariable Long id){
        return service.LoadById(id);
    }

    @GetMapping
    @ApiOperation(value = "通过查询所有")
    @PreAuthorize(name = "查询所有部门",sn = "department:list")
    public List<Department> loadAll(){
        return service.loadAll();
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "通过id删除所有")
    @PreAuthorize(name = "删除部门",sn = "department:delete")
    public AjaxResult remove(@ApiParam(name="ID属性",required = true) @PathVariable Long id){
        try {
            service.removeById(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙");
        }
    }

    @PutMapping
    @ApiOperation(value = "新增或者修改")
    @PreAuthorize(name = "新增/修改部门",sn = "department:addOrupt")
    public AjaxResult addOrupt(@ApiParam(name="对象",required = true) @RequestBody Department department){
        try {
            if (department.getId() == null){
                service.save(department);
            }else {
                service.upadte(department);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙");
        }
    }

    @PostMapping
    @ApiOperation(value = "高级查询和分页")
    @PreAuthorize(name = "查询部门",sn = "department:query")
    public PageList<Department> queryDept(@ApiParam(name="查询条件和分页",required = true) @RequestBody DepartmentQuery deptQuery ){

        return service.query(deptQuery);
    }

    @PatchMapping
    public AjaxResult patchRom(@RequestBody Long[] ids){
        try {
            service.patchRom(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙");
        }
    }

    @GetMapping("/tree")
    public List<Department> loadTree(){
        return service.loadTree();
    }

}
